/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pt.iasd.youthshelter.datacore.controller;

import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import pt.iasd.youthshelter.datamodel.PathfinderRole;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import org.openide.util.lookup.ServiceProvider;
import pt.iasd.youthshelter.datacore.EntityManagerSemaphore;
import pt.iasd.youthshelter.datacore.controller.exceptions.IllegalOrphanException;
import pt.iasd.youthshelter.datacore.controller.exceptions.NonexistentEntityException;
import pt.iasd.youthshelter.datamodel.Role;
import pt.iasd.youthshelter.datamodel.service.RoleController;

/**
 *
 * @author Rui
 */
@ServiceProvider(service=RoleController.class)
public class RoleJpaController implements Serializable, RoleController {

    private EntityManager aquireEntityManager() throws InterruptedException {
        EntityManagerSemaphore.getInstance().getSemaphore().acquire();
        return EntityManagerSemaphore.getInstance().getEntityManager();
    }
    
    private void releaseEntityManager(EntityManager em) {
        if (em != null && em.isOpen()) {
            em.close();
        }
        EntityManagerSemaphore.getInstance().getSemaphore().release();
    }

    @Override
    public void create(Role role) {
        if (role.getPathfinderRoleList() == null) {
            role.setPathfinderRoleList(new ArrayList<PathfinderRole>());
        }
        EntityManager em = null;
        try {
            em = aquireEntityManager();
            em.getTransaction().begin();
            List<PathfinderRole> attachedPathfinderRoleList = new ArrayList<PathfinderRole>();
            for (PathfinderRole pathfinderRoleListPathfinderRoleToAttach : role.getPathfinderRoleList()) {
                pathfinderRoleListPathfinderRoleToAttach = em.getReference(pathfinderRoleListPathfinderRoleToAttach.getClass(), pathfinderRoleListPathfinderRoleToAttach.getId());
                attachedPathfinderRoleList.add(pathfinderRoleListPathfinderRoleToAttach);
            }
            role.setPathfinderRoleList(attachedPathfinderRoleList);
            em.persist(role);
            for (PathfinderRole pathfinderRoleListPathfinderRole : role.getPathfinderRoleList()) {
                Role oldRoleIdOfPathfinderRoleListPathfinderRole = pathfinderRoleListPathfinderRole.getRoleId();
                pathfinderRoleListPathfinderRole.setRoleId(role);
                pathfinderRoleListPathfinderRole = em.merge(pathfinderRoleListPathfinderRole);
                if (oldRoleIdOfPathfinderRoleListPathfinderRole != null) {
                    oldRoleIdOfPathfinderRoleListPathfinderRole.getPathfinderRoleList().remove(pathfinderRoleListPathfinderRole);
                    em.merge(oldRoleIdOfPathfinderRoleListPathfinderRole);
                }
            }
            em.getTransaction().commit();
        } catch(InterruptedException ex) {
        } finally {
            releaseEntityManager(em);
        }
    }

    @Override
    public void edit(Role role) throws IllegalOrphanException, NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = aquireEntityManager();
            em.getTransaction().begin();
            Role persistentRole = em.find(Role.class, role.getId());
            List<PathfinderRole> pathfinderRoleListOld = persistentRole.getPathfinderRoleList();
            List<PathfinderRole> pathfinderRoleListNew = role.getPathfinderRoleList();
            List<String> illegalOrphanMessages = null;
            for (PathfinderRole pathfinderRoleListOldPathfinderRole : pathfinderRoleListOld) {
                if (!pathfinderRoleListNew.contains(pathfinderRoleListOldPathfinderRole)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain PathfinderRole " + pathfinderRoleListOldPathfinderRole + " since its roleId field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            List<PathfinderRole> attachedPathfinderRoleListNew = new ArrayList<PathfinderRole>();
            for (PathfinderRole pathfinderRoleListNewPathfinderRoleToAttach : pathfinderRoleListNew) {
                pathfinderRoleListNewPathfinderRoleToAttach = em.getReference(pathfinderRoleListNewPathfinderRoleToAttach.getClass(), pathfinderRoleListNewPathfinderRoleToAttach.getId());
                attachedPathfinderRoleListNew.add(pathfinderRoleListNewPathfinderRoleToAttach);
            }
            pathfinderRoleListNew = attachedPathfinderRoleListNew;
            role.setPathfinderRoleList(pathfinderRoleListNew);
            role = em.merge(role);
            for (PathfinderRole pathfinderRoleListNewPathfinderRole : pathfinderRoleListNew) {
                if (!pathfinderRoleListOld.contains(pathfinderRoleListNewPathfinderRole)) {
                    Role oldRoleIdOfPathfinderRoleListNewPathfinderRole = pathfinderRoleListNewPathfinderRole.getRoleId();
                    pathfinderRoleListNewPathfinderRole.setRoleId(role);
                    pathfinderRoleListNewPathfinderRole = em.merge(pathfinderRoleListNewPathfinderRole);
                    if (oldRoleIdOfPathfinderRoleListNewPathfinderRole != null && !oldRoleIdOfPathfinderRoleListNewPathfinderRole.equals(role)) {
                        oldRoleIdOfPathfinderRoleListNewPathfinderRole.getPathfinderRoleList().remove(pathfinderRoleListNewPathfinderRole);
                        em.merge(oldRoleIdOfPathfinderRoleListNewPathfinderRole);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = role.getId();
                if (findRole(id) == null) {
                    throw new NonexistentEntityException("The role with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            releaseEntityManager(em);
        }
    }

    @Override
    public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException {
        EntityManager em = null;
        try {
            em = aquireEntityManager();
            em.getTransaction().begin();
            Role role;
            try {
                role = em.getReference(Role.class, id);
                role.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The role with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            List<PathfinderRole> pathfinderRoleListOrphanCheck = role.getPathfinderRoleList();
            for (PathfinderRole pathfinderRoleListOrphanCheckPathfinderRole : pathfinderRoleListOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Role (" + role + ") cannot be destroyed since the PathfinderRole " + pathfinderRoleListOrphanCheckPathfinderRole + " in its pathfinderRoleList field has a non-nullable roleId field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            em.remove(role);
            em.getTransaction().commit();
        } catch(InterruptedException ex) {
        } finally {
            releaseEntityManager(em);
        }
    }

    @Override
    public List<Role> findRoleEntities() {
        return findRoleEntities(true, -1, -1);
    }

    @Override
    public List<Role> findRoleEntities(int maxResults, int firstResult) {
        return findRoleEntities(false, maxResults, firstResult);
    }

    private List<Role> findRoleEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = null;
        try {
            em = aquireEntityManager();
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Role.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } catch(InterruptedException ex) {
        } finally {
            releaseEntityManager(em);
        }
        return null;
    }

    @Override
    public Role findRole(Integer id) {
        EntityManager em = null;
        try {
            em = aquireEntityManager();
            return em.find(Role.class, id);
        } catch(InterruptedException ex) {
        } finally {
            releaseEntityManager(em);
        }
        return null;
    }

    @Override
    public int getRoleCount() {
        EntityManager em = null;
        try {
            em = aquireEntityManager();
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Role> rt = cq.from(Role.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } catch(InterruptedException ex) {
        } finally {
            releaseEntityManager(em);
        }
        return 0;
    }
    
}
